package com.nondo.rdp.finance.endpoint.api.app;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.Message;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.auth.event.PushApplicationEvent;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.domain.attach.Attach;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.circle.Circle;
import com.nondo.rdp.finance.domain.circle.CircleComment;
import com.nondo.rdp.finance.domain.circle.CircleUp;
import com.nondo.rdp.finance.model.circle.CircleBean;
import com.nondo.rdp.finance.model.circle.CircleCommentBean;
import com.nondo.rdp.finance.model.circle.CircleQuery;
import com.nondo.rdp.finance.service.AttachService;
import com.nondo.rdp.finance.service.circle.CircleCommentService;
import com.nondo.rdp.finance.service.circle.CircleService;
import com.nondo.rdp.finance.service.circle.CircleUpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * 圈子
 */
@RestController("apiAppCircle")
@RequestMapping("/api/app/circle")
public class CircleEndpoint {
	
    @Autowired
    CircleService circleService;

    @Autowired
    UserService userService;

    @Autowired
    CircleCommentService circleCommentService;

    @Autowired
    CircleUpService circleUpService;
    
    @Autowired
    AttachService attachService;
    
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    
    @RequestMapping("/info/{id}")
    public View<CircleQuery> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
		View<CircleQuery> view = new View<CircleQuery>(20000, "获取数据成功");

		Circle circleDb = null;
		CircleQuery cq = null;
		if (id != null) {
			circleDb = circleService.findOne(id);
			if (circleDb == null) {
				return View.ofError("您查看的说说不存在");
			}
			cq = this.circleService.getCircleDetail(circleDb);
		} else {
			cq = new CircleQuery();
		}

		view.setData(cq);
		return view;
    }
    
    @RequestMapping("/list")
    public View<Page<CircleQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<CircleBean> query) {
        View<Page<CircleQuery>> view = new View<Page<CircleQuery>>(20000, "获取列表成功");

        CircleBean circleBean = query.getData();

        Page<Circle> page = circleService.findAll(new Page<Circle>(query.getPage(), query.getSize()), circleBean);
        
        Page<CircleQuery> resultPage = page.convertPage(new ConvertCall<Circle,Page<CircleQuery>>(){

			@Override
			public Page<CircleQuery> execute(Page<Circle> srcPage) {
				
				Page<CircleQuery> circleQueryPage = new Page<CircleQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
				
				List<CircleQuery> cqList = new ArrayList<CircleQuery>();

				List<Circle> cricleList = srcPage.getContent();

				for (Circle circleDb : cricleList) {
					CircleQuery cq = circleService.getCircleDetail(circleDb);
					cqList.add(cq);
				}
				circleQueryPage.setContent(cqList);
				return circleQueryPage;
			}
        	
        });
        
        view.setData(resultPage);

        return view;
    }

    @RequestMapping("/add")
    public View<CircleBean> add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CircleBean circle, BindingResult result) {
        View<CircleBean> view = new View<CircleBean>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
        	User user = UserUtils.getUser(request, response);
            Circle circleDb = new Circle();
            BeanUtils.copy(circle, circleDb);
			circleDb.setUser(user);
            String imagePathStr = circle.getImagePaths();
			if (StringUtils.isNotBlank(imagePathStr)) {
				List<Attach> attachList = new ArrayList<Attach>();
				String[] imagePaths = imagePathStr.split(",");
				for (String imagePath : imagePaths) {
					Attach attach = new Attach();
					attach.setPath(imagePath);
					attach.setRemark("说说");
					attach.setType(0);
					attachService.save(attach);
					attachList.add(attach);
					circleDb.setAttachList(attachList);
				}
            }
			this.circleService.save(circleDb);
            CircleBean circleBean = CircleBean.covert2Bean(circleDb);
            view.setData(circleBean);
        }
        return view;
    }

    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");
        User user = UserUtils.getUser(request, response);
        Circle circle = this.circleService.findOne(id);
		if (!user.getId().equals(circle.getUser().getId())) {
			view.setCode(50000);
			view.setMessage("对不起，你没有权限进行操作");
			return view;
		}
        this.circleService.delete(id);

        return view;
    }

    @RequestMapping("/comment")
    public View<CircleQuery> comment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CircleCommentBean circleCommentBean, BindingResult result) {
        View<CircleQuery> view = new View<CircleQuery>(20000, "评论成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
        	User user = UserUtils.getUser(request, response);
			Circle circle = this.circleService.findOne(circleCommentBean.getCircleId());
			
			if (circle == null) {
				view.setCode(40000);
				view.setMessage("评论的说说不存在");
				return view;
			}
			CircleComment circleComment = new CircleComment();
			BeanUtils.copy(circleCommentBean, circleComment);
			circleComment.setUser(user);
			circleComment.setCircle(circle);
			User toUser = null;
			Long toUserId = circleCommentBean.getToUserId();
			if (toUserId != null) {
				toUser = this.userService.findOne(toUserId);
			}
			circleComment.setToUser(toUser);
			this.circleCommentService.save(circleComment);
			
			//重新加载
			CircleQuery cq = this.circleService.getCircleDetail(circle);
			view.setData(cq);
			
			//消息推送
			if (!user.getId().equals(circle.getUser().getId())) {
				toUser = circleComment.getToUser();
				if (toUser == null) {
					toUser = circle.getUser();
				}
				String uid = toUser.getId().toString();
				Message message = new Message();
				message.setTitle("评论消息提醒");
				message.setContent(user.getNickName() + "评论了你的说说，赶快去看看吧");
				message.setMethod("circle");
				message.setExtra(circle.getId().toString());
				message.setType(2);
				message.setUids(uid);

				applicationEventPublisher.publishEvent(new PushApplicationEvent(this, message));
			}
        }

        return view;
    }

    @RequestMapping("/comment/delete/{id}")
    public View commentDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");
        User user = UserUtils.getUser(request, response);
        CircleComment comment = this.circleCommentService.findOne(id);
		if (!user.getId().equals(comment.getUser().getId())) {
			view.setCode(50000);
			view.setMessage("对不起，你没有权限进行操作");
			return view;
		}
        this.circleCommentService.delete(id);

        return view;
    }

    @RequestMapping("/up/{id}")
    public View<CircleQuery> up(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<CircleQuery> view = new View<CircleQuery>(20000, "点赞成功");

		// 检查该用户是否已经点过赞了
        User user = UserUtils.getUser(request, response);
        Circle circle = this.circleService.findOne(id);
        
        CircleUp circleUp = this.circleUpService.check(circle.getId(), user.getId());
        if (circleUp == null) {
        	 circleUp = new CircleUp();
        	 circleUp.setCircle(circle);
        	 circleUp.setUser(user);
             this.circleUpService.save(circleUp);
             
             //消息推送
			if (!user.getId().equals(circle.getUser().getId())) {
				User toUser = circleUp.getCircle().getUser();
				String uid = toUser.getId().toString();
				Message message = new Message();
				message.setTitle("点赞消息提醒");
				message.setContent(user.getNickName() + "给你点了一个赞，赶快去看看吧");
				message.setMethod("circle");
				message.setExtra(circle.getId().toString());
				message.setType(2);
				message.setUids(uid);

				applicationEventPublisher.publishEvent(new PushApplicationEvent(this, message));
			}
        } else {
			view.setCode(20000);
			view.setMessage("取消点赞成功");
            this.circleUpService.delete(circleUp.getId());
        }
        
        //重新加载
        CircleQuery cq = this.circleService.getCircleDetail(circle);
        view.setData(cq);
        
        return view;
    }

}
